<template>
  <div>
    <h2 style="text-align: center; margin: 20px 0;">座位预约</h2>
    <div style="text-align: center;">
      <el-tag type="info">未选</el-tag>
      <el-tag type="warning">待选</el-tag>
      <el-tag type="success">已选</el-tag>
    </div>

    <div class="seat-grid">
      <div
          v-for="seat in data.seats"
          :key="seat.id"
          :class="[
          'seat',
          seat.status === '已选' ? 'reserved' :
          data.tempSelectedId === seat.id ? 'selected' : ''
        ]"
          @click="toggleSeat(seat)"
      >
        {{ seat.no }}
      </div>
    </div>

    <div style="text-align: center; margin-top: 20px;">
      <el-button type="primary" @click="submitReserve">预约座位</el-button>
    </div>
  </div>
</template>

<script setup>
import { reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import router from '@/router/index.js'

const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || '{}'),
  roomId: router.currentRoute.value.query.id,
  seats: [],
  tempSelectedId: null,
  seat: {}
})

const loadSeats = () => {
  request.get('/seat/selectAll', {
    params: {
      roomId: data.roomId
    }
  }).then(res => {
    if (res.code === '200') {
      data.seats = res.data
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const toggleSeat = (seat) => {
  if (seat.status === '已选') return  // 已预约不可点击

  // 再次点击取消选中
  if (data.tempSelectedId === seat.id) {
    data.tempSelectedId = null
    data.seat = {}
  } else {
    data.tempSelectedId = seat.id
    data.seat = { ...seat }  // 拷贝一份用于提交
  }
}

const submitReserve = () => {
  if (!data.tempSelectedId) return ElMessage.warning('请选择一个座位')
  data.seat.status = '已选'
  data.seat.userName=data.user.username
  request.put('/seat/update', data.seat).then(res => {
    if (res.code === '200') {
      ElMessage.success('预约成功')
      data.tempSelectedId = null
      loadSeats()
    } else {
      ElMessage.error(res.msg)
    }
  })
}

onMounted(loadSeats)
</script>

<style scoped>
.seat-grid {
  display: grid;
  grid-template-columns: repeat(5, 60px);
  gap: 15px;
  justify-content: center;
  margin-top: 30px;
}

.seat {
  width: 60px;
  height: 60px;
  background-color: #f2f2f2; /* 默认灰色 */
  border: 1px solid #ccc;
  line-height: 60px;
  text-align: center;
  border-radius: 4px;
  cursor: pointer;
  transition: 0.2s;
}

.seat.selected {
  background-color: orange; /* 临时选中（点击后）橙色 */
  color: #fff;
}

.seat.reserved {
    background-color: #67C23A; /* 已预约状态绿色 */
  color: #fff;
  cursor: not-allowed;
}
</style>
